package top.jle.wx.proxy.facade.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import top.jle.wx.proxy.domain.templateMsg.TemplateMessage;
import top.jle.wx.proxy.feign.ResultCheckUtil;
import top.jle.wx.proxy.feign.templateMsg.TemplateMsgAPIFeign;
import top.jle.wx.proxy.util.GlobalThreadLocalUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
public class BatchSender {

    private static final Logger LOGGER = LoggerFactory.getLogger(BatchSender.class);
    @Autowired
    private TemplateMsgAPIFeign templateMsgAPIFeign;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Async
    public void batchSend(Set<String> openids, TemplateMessage option, String queueId, String accessToken){
        GlobalThreadLocalUtil.setAccessToken(accessToken);
        for(String openid : openids){
            option.setTouser(openid);
            JSONObject result = templateMsgAPIFeign.send((JSONObject) JSON.toJSON(option));
            LOGGER.info(result.toJSONString());
            if(ResultCheckUtil.check(result)){
                stringRedisTemplate.opsForSet().add("msg_queue_"+queueId,result.getString("msgid"));
            }else{
                LOGGER.info("openid={},发送失败",openid);
            }

        }
        stringRedisTemplate.expire("msg_queue_"+queueId,1L,TimeUnit.DAYS);
    }
}
